<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="拨号时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="拨打人" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属班级" prop="classId">
            <class-tree v-model="queryParams.classId" gradeDisabled />
            <!-- <el-input v-model="queryParams.classId" placeholder="请输入班级ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <!-- <el-autocomplete
              v-model="queryParams.className"
              :fetch-suggestions="searchClassInfo"
              :trigger-on-focus="false"
              placeholder="请选择班级"
              clearable
              @select="((e) => { queryParams.classId = e.id;  queryParams.className = e.className; })"
            >
              <template #default="{ item }">
                <div class="value">{{ item.className }}</div>
              </template>
            </el-autocomplete> -->
          </el-form-item>
          <el-form-item label="接听人" prop="contactName">
            <el-input v-model="queryParams.contactName" placeholder="请输入接听人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="contactPhone">
            <el-input v-model="queryParams.contactPhone" placeholder="请输入联系人手机号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="拨打状态" prop="callStatus">
            <el-select v-model="queryParams.callStatus" placeholder="请选择拨打状态" clearable>
              <el-option v-for="dict in call_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="联系人类型：1监护人，2教职工" prop="contactType">
            <el-select v-model="queryParams.contactType" placeholder="请选择联系人类型：1监护人，2教职工" clearable>
              <el-option v-for="dict in contact_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="拨打方式" prop="callWay">
            <el-select v-model="queryParams.callWay" placeholder="请选择拨打方式" clearable>
              <el-option v-for="dict in call_way" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="拨打时长" prop="calculateTime">
            <el-input v-model="queryParams.calculateTime" placeholder="请输入拨打时长" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="通话类型" prop="calleeType">
            <el-select v-model="queryParams.calleeType" placeholder="请选择通话类型" clearable>
              <el-option v-for="dict in callee_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="开始通话时间" prop="startTime">
            <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始通话时间" />
          </el-form-item>
          <el-form-item label="结束通话时间" prop="endTime">
            <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束通话时间" />
          </el-form-item> -->
          <!-- <el-form-item label="设备ID" prop="deviceId">
            <el-input v-model="queryParams.deviceId" placeholder="请输入设备ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="设备系列" prop="deviceSeries">
            <el-input v-model="queryParams.deviceSeries" placeholder="请输入设备系列" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="话机系列" prop="deviceSeries">
            <el-select v-model="queryParams.deviceSeries" placeholder="请选择设备系列" clearable>
              <el-option v-for="dict in tel_device_series" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:telCallRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:telCallRecord:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:telCallRecord:remove']"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:telCallRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 420px)"
        stripe
        v-loading="loading"
        :data="telCallRecordList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleDetail(row)"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="拨打人" align="center" prop="studentName" />
        <el-table-column label="班级" align="center" prop="className" />
        <el-table-column label="接听人" align="center" prop="contactName" />
        <el-table-column label="接听人类型" align="center" prop="contactType" width="120">
          <template #default="scope">
            <dict-tag :options="contact_type" :value="scope.row.contactType" />
          </template>
        </el-table-column>
        <el-table-column label="拨打电话" align="center" prop="contactPhone" width="160" />
        <el-table-column label="拨打方式" align="center" prop="callWay">
          <template #default="scope">
            <dict-tag :options="call_way" :value="scope.row.callWay" />
          </template>
        </el-table-column>
        <el-table-column label="拨打状态" align="center" prop="callStatus" width="120">
          <template #default="scope">
            <dict-tag :options="call_status" :value="scope.row.callStatus" />
          </template>
        </el-table-column>
        <el-table-column label="通话时长(分)" align="center" prop="calculateTime" width="120" />
        <el-table-column label="通话类型" align="center" prop="calleeType">
          <template #default="scope">
            <dict-tag :options="callee_type" :value="scope.row.calleeType" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="开始通话时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束通话时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="拨号时间" align="center" prop="callTime" width="160" />
        <!-- <el-table-column label="设备ID" align="center" prop="deviceId" /> -->
        <el-table-column label="设备名称" align="center" prop="deviceName" width="160" />
        <!-- <el-table-column label="设备系列" align="center" prop="deviceSeries" width="160">
          <template #default="scope">
            <dict-tag :options="tel_device_series" :value="scope.row.deviceSeries" />
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:telCallRecord:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:telCallRecord:remove']"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改通话记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="760px" append-to-body>
      <el-form ref="telCallRecordFormRef" :inline="true" :model="form" :rules="rules" label-width="110px" class="add-form" disabled>
        <el-form-item label="拨打人" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生" />
        </el-form-item>
        <el-form-item label="接听人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="拨打电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人手机号" />
        </el-form-item>
        <el-form-item label="联系人类型" prop="contactType">
          <el-select v-model="form.contactType" placeholder="请选择联系人类型">
            <el-option v-for="dict in contact_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拨打方式" prop="callWay">
          <el-select v-model="form.callWay" placeholder="请选择拨打方式">
            <el-option v-for="dict in call_way" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通话时长(分)" prop="calculateTime">
          <el-input v-model="form.calculateTime" placeholder="请输入拨打时长" />
        </el-form-item>
        <el-form-item label="通话类型" prop="calleeType">
          <el-select v-model="form.calleeType" placeholder="请选择通话类型">
            <el-option v-for="dict in callee_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始通话时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始通话时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束通话时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束通话时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item> -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- <el-form-item label="设备系列" prop="deviceSeries">
          <el-input v-model="form.deviceSeries" placeholder="请输入设备系列" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
        <el-form-item label="拨打状态" prop="callStatus">
          <el-select v-model="form.callStatus" placeholder="请选择拨打状态">
            <el-option v-for="dict in call_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="TelCallRecord" lang="ts">
import { listTelCallRecord, getTelCallRecord, delTelCallRecord, addTelCallRecord, updateTelCallRecord } from '@/api/device/telCallRecord';
import { TelCallRecordVO, TelCallRecordQuery, TelCallRecordForm } from '@/api/device/telCallRecord/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { contact_type, call_way, callee_type, tel_device_series, call_status } = toRefs<any>(
  proxy?.useDict('contact_type', 'call_way', 'callee_type', 'tel_device_series', 'call_status')
);

const telCallRecordList = ref<TelCallRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const telCallRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TelCallRecordForm = {
  id: undefined,
  studentId: undefined,
  classId: undefined,
  contactName: undefined,
  contactPhone: undefined,
  contactType: undefined,
  callWay: undefined,
  callStatus: undefined,
  calculateTime: undefined,
  calleeType: undefined,
  startTime: undefined,
  endTime: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceSeries: undefined,
  remark: undefined
};
const data = reactive<PageData<TelCallRecordForm, TelCallRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    classId: undefined,
    contactName: undefined,
    contactPhone: undefined,
    contactType: undefined,
    callWay: undefined,
    callStatus: undefined,
    calculateTime: undefined,
    calleeType: undefined,
    startTime: undefined,
    endTime: undefined,
    deviceId: undefined,
    deviceName: undefined,
    deviceSeries: undefined,
    params: {
      createTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生ID不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级ID不能为空', trigger: 'blur' }],
    contactName: [{ required: true, message: '联系人姓名不能为空', trigger: 'blur' }],
    contactPhone: [{ required: true, message: '联系人手机号不能为空', trigger: 'blur' }],
    contactType: [{ required: true, message: '联系人类型：1监护人，2教职工不能为空', trigger: 'change' }],
    callWay: [{ required: true, message: '拨打方式：1刷脸、2刷卡不能为空', trigger: 'change' }],
    callStatus: [{ required: true, message: '拨打状态：1拨号失败、2被叫拒接接听、3主动取消拨打、4通话结束、5响铃失败不能为空', trigger: 'change' }],
    calculateTime: [{ required: true, message: '拨打时长不能为空', trigger: 'blur' }],
    calleeType: [{ required: true, message: '通话类型：1语音通话，2视频通话不能为空', trigger: 'change' }],
    startTime: [{ required: true, message: '开始通话时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '结束通话时间不能为空', trigger: 'blur' }],
    deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    deviceSeries: [{ required: true, message: '设备系列不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询通话记录列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CallTime');
  const res = await listTelCallRecord(queryParams.value);
  telCallRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  telCallRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.className = undefined;
  handleQuery();
};

import { listClassInfo } from '@/api/office/class';

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TelCallRecordVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加通话记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TelCallRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTelCallRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改通话记录';
};

const handleDetail = async (row?: TelCallRecordVO) => {
  reset();
  Object.assign(form.value, row);
  dialog.visible = true;
  dialog.title = '详情';
};

/** 提交按钮 */
const submitForm = () => {
  telCallRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTelCallRecord(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTelCallRecord(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TelCallRecordVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.deviceText + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delTelCallRecord(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/telCallRecord/export',
    {
      ...queryParams.value
    },
    `telCallRecord_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
